package com.penghaonan.appframework

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.content.res.AppCompatResources
import com.penghaonan.appframework.base.BaseFrameworkActivity
import com.penghaonan.appframework.reporter.Reporter
import com.penghaonan.appframework.utils.ActivityLifecycleCallbackAdapter
import com.penghaonan.appframework.utils.Logger
import com.penghaonan.appframework.utils.threadpool.IOThreadPool
import com.penghaonan.appframework.utils.threadpool.ThreadPoolTask

object AppDelegate {
    /**
     * 获取单例实例
     */
    private var mHandler: Handler = Handler(Looper.getMainLooper())
    var mIsDebug = false
    private var iOThreadPool: IOThreadPool? = null
    private lateinit var _app: Application

    @JvmStatic
    fun getIOThreadPool(): IOThreadPool {
        return iOThreadPool!!
    }

    @JvmStatic
    fun getApp(): Application {
        return _app
    }

    /**
     * 在应用Application.onCreate()方法中调用
     */

    fun prepare(application: Application) {
        _app = application
        Reporter.init()
        iOThreadPool = IOThreadPool()

        val mActivityLifecycleCallback: Application.ActivityLifecycleCallbacks =
            object : ActivityLifecycleCallbackAdapter() {
                override fun onActivityResumed(activity: Activity) {
                    Reporter.getInstance().onActivityResume(activity)
                }

                override fun onActivityPaused(activity: Activity) {
                    Reporter.getInstance().onActivityPause(activity)
                }
            }
        getApp().registerActivityLifecycleCallbacks(mActivityLifecycleCallback)
    }

    @JvmStatic
    var isDebug: Boolean
        get() = mIsDebug
        set(isDebug) {
            mIsDebug = isDebug
            Logger.enable = isDebug
        }

    /**
     * 获取字符串
     */
    @JvmStatic
    fun getString(resId: Int): String {
        return getApp().getString(resId)
    }

    @JvmStatic
    fun getString(resId: Int, vararg formatArgs: Any?): String {
        return getApp().getString(resId, *formatArgs)
    }

    @JvmStatic
    fun getDrawable(resId: Int): Drawable? {
        return AppCompatResources.getDrawable(getApp(), resId)
    }

    /**
     * 主线程执行
     */
    @JvmStatic
    fun post(runnable: Runnable) {
        mHandler.post(runnable)
    }

    /**
     * 主线程延迟执行
     */
    @JvmStatic
    fun postDelayed(runnable: Runnable, delay: Long) {
        mHandler.postDelayed(runnable, delay)
    }

    /**
     * 取消执行
     */
    fun removeCallbacks(runnable: Runnable) {
        mHandler.removeCallbacks(runnable)
    }

    @JvmStatic
    fun postAsync(task: ThreadPoolTask?) {
        iOThreadPool!!.addTask(task)
    }

    fun cancelAsync(task: ThreadPoolTask?) {
        iOThreadPool!!.cancel(task)
    }

    /**
     * 打开activity
     */
    fun startActivity(activityCls: Class<out Activity?>?, bundle: Bundle?): Boolean {
        val intent = Intent(getApp(), activityCls)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        return startActivity(intent)
    }

    @JvmOverloads
    @JvmStatic
    fun startActivity(
        context: Context,
        intent: Intent,
        callback: ((Any?) -> Unit)? = null
    ): Boolean {
        if (context is Activity) {
            try {
                if (callback != null) {
                    val lifecycleCallbackAdapter = object : ActivityLifecycleCallbackAdapter() {
                        override fun onActivityCreated(
                            activity: Activity,
                            savedInstanceState: Bundle?
                        ) {
                            super.onActivityCreated(activity, savedInstanceState)
                            if (activity is BaseFrameworkActivity) {
                                activity.resultCallback = {
                                    callback(it)
                                }
                            }
                            getApp().unregisterActivityLifecycleCallbacks(this)
                        }
                    }
                    getApp().registerActivityLifecycleCallbacks(lifecycleCallbackAdapter)
                }
                context.startActivity(intent)
                return true
            } catch (e: Exception) {
                Logger.e(e)
            }
            return false
        } else {
            return startActivity(intent)
        }
    }

    fun startActivity(intent: Intent): Boolean {
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            getApp().startActivity(intent)
            return true
        } catch (e: Exception) {
            Logger.e(e)
        }
        return false
    }

    @JvmStatic
    fun getVersionCode(): Long {
        try {
            return getApp().packageManager.getPackageInfo(
                getApp().packageName,
                0
            ).versionCode.toLong()
        } catch (e: PackageManager.NameNotFoundException) {
            Logger.e(e)
            return 0
        }
    }
}
